$(function () {
    var lis = document.querySelectorAll("#news li");
    var len = lis.length;

    //切换页签样式：遍历li，给li绑定onclick事件
    for (var i = 0; i < len; i++) {
        lis[i].onclick = function () {
            //切换页签样式↓
            for (var i = 0; i < len; i++) {
                if (lis[i] == this) {//判断是否为当前对象
                    lis[i].style.background = "rosybrown";
                    lis[i].querySelector("a").style.color = "white";
                    var news_id = lis[i].querySelector("a").id;
                    // if (news_id == "list_news") {
                    //     $("#news_list").css("display", "block");
                    //     $("#news_import").css("display", "none");
                    // } else {
                    //     $("#news_list").css("display", "none");
                    //     $("#news_import").css("display", "block");
                    // }
                } else {
                    lis[i].style.background = "white";
                    lis[i].querySelector("a").style.color = "black";
                }
            }
        }
    }

    // var ip = 'http://192.168.83.128:8088';
    var _orderType = 0;
    var _page = 1;
    var _type = 0;
//基本行为列表
    function getNews(orderType = 0, page = 1, type = 0) {
        _orderType = orderType;
        _page = page;
        _type = type;
        var btnText = '';
        // _type==1?btnText='移除重要新闻':btnText="设为重要新闻";
        var _timestamp = new Date().getTime();
        var _secret = hex_md5(ip + '/NewsBack/GetNewsList?timestamp=' + _timestamp + salt);
        var _id = $(this).parent().parent().attr("_id");
        var that = $(this).parent().parent();
        $.ajax({
            type: "POST",
            url: ip + '/NewsBack/GetNewsList?timestamp=' + _timestamp + '&secret=' + _secret + '&token=' + _token,
            dataType: 'json',
            data: JSON.stringify({
                "orderType": orderType, //(integer, optional): 1为股票排序 其余为时间排序 ,
                "page": page,  //(integer, optional): 页数 一页20个 ,
                "type": type //(integer, optional): 1为重要 其余为全部
            }),
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json;charset=utf-8",
                // "token": "Zo0hVZ6QH3BoyyrLCp1dJO9qygX60uwrFJo1fWTkdbGFGKnEvblzgw%3D%3D"
                "token": _token
            },
            success: function (data) {
                // var result = JSON.stringify(data);
                console.log(data);
                if (data.code == 1) {
                    // 基本行为列表
                    if (_type == 0) {
                        if (page == 1) {
                            $("#news_list div").remove();
                        }
                        var count = data.data.length;
                        count == 0 ? $("#hrDx").show() : $("#hrDx").hide();
                        for (let i = 0; i < count; i++) {
                            var type0 = data.data[i].type == 1 ? btnText = ' 移除重要新闻' : btnText = " 设为重要新闻";
                            var newsView = `<div class="divLi ${data.data[i].type == 1 ? "import_div" : ""}" newsid=${data.data[i].newsid}><a href=${data.data[i].url} target="view_window"><h4>${data.data[i].title}</h4></a>
                    <!--<label><img src="img/sort-up.png"></label><label><img src="img/sort-up.png"></label>-->
                    <span class="btn updateNews" type=${data.data[i].type == 1 ? 0 : 1}><i class="icon-star"></i>${type0}</span><label class="lable_box">&nbsp;${data.data[i].author}&nbsp;</label><label class="lable_box_2" code=${data.data[i].code}>&nbsp;${data.data[i].companyname}&nbsp;</label><label>${transDate(data.data[i].publishtime)}</label>
                    <!--<span class="spanX"><i class=" icon-star"></i></span>-->
                    </div>`;
                            $("#news_list").append(newsView);
                        }
                    }
                    //重要新闻列表
                    if (_type == 1) {
                        if (page == 1) {
                            $("#news_list div").remove();
                        }
                        var count = data.data.length;
                        count == 0 ? $("#hrDx").show() : $("#hrDx").hide();
                        for (let i = 0; i < count; i++) {
                            var type0 = data.data[i].type == 1 ? btnText = '移除重要新闻' : btnText = "设为重要新闻";
                            var newsView = `<div class="divLi ${data.data[i].type == 1 ? "111" : ""}" newsid=${data.data[i].newsid}><a href=${data.data[i].url} target="view_window"><h4>${data.data[i].title}</h4></a>
                    <!--<label><img src="img/sort-up.png"></label><label><img src="img/sort-up.png"></label>-->
                    <label class="lable_box">&nbsp;${data.data[i].author}&nbsp;</label><label class="lable_box_2" code=${data.data[i].code}>&nbsp;${data.data[i].companyname}&nbsp;</label><label>${transDate(data.data[i].publishtime)}</label>
                    <!--<button class="btn updateNews"><i class="icon-star"></i>${type0}</button>-->
                    <span class="updateNews spanX" type=${_type == 1 ? 0 : 1}><i class=" icon-remove"></i></span>
                    </div>`;
                            $("#news_list").append(newsView);
                        }
                    }
                    newsViewAndUpdate();
                }
                else {
                    alert(data.message)
                }
            },
            error: function () {
                alert('请求失败');
            },
        });
    }

    getNews();

    //修改新闻重要性
    function pudateNews() {

    }

    //orderType(integer, optional): 1为股票排序 其余为时间排序 ,
    //page(integer, optional): 页数 一页20个 ,
    //type(integer, optional): 1为重要 其余为全部

    //普通新闻列表
    $("#list_news").click(function () {
        _type = 0;
        getNews(0, 1, _type)
    });
    //重要新闻列表
    $("#import_news").click(function () {
        _type = 1;
        getNews(0, 1, _type)
    });
    //按照时间排序
    $("#byTime").click(function () {
        _orderType = 0;
        getNews(_orderType, 1, _type)
    });
    //按照股票排序
    $("#byStock").click(function () {
        _orderType = 1;
        getNews(_orderType, 1, _type)
    });
    //分页
    $("#pageUp").click(function () {
        _page == 1 ? _page = 1 : _page -= 1;
        getNews(_orderType, _page, _type)

    });
    $("#pageDown").click(function () {
        _page += 1;
        getNews(_orderType, _page, _type)
    });
    $("#pageOne").click(function () {
        _page = 1;
        getNews(_orderType, _page, _type)
    });

    //设置重要新闻 通过股票代码查询新闻
    function newsViewAndUpdate() {
        //通过股票新闻查询新闻
        $(".lable_box_2").unbind("click");
        $(".lable_box_2").click(function () {
            var _timestamp = new Date().getTime();
            var _secret = hex_md5(ip + '/NewsBack/GetNewsListByCode?timestamp=' + _timestamp + salt);
            var _code = $(this).attr("code");
            $.ajax({
                type: "POST",
                url: ip + '/NewsBack/GetNewsListByCode?timestamp=' + _timestamp + '&secret=' + _secret + '&token=' + _token,
                dataType: 'json',
                data: JSON.stringify({
                    "code": _code
                }),
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json;charset=utf-8",
                    // "token": "Zo0hVZ6QH3BoyyrLCp1dJO9qygX60uwrFJo1fWTkdbGFGKnEvblzgw%3D%3D"
                    "token": _token
                },
                success: function (data) {
                    // var result = JSON.stringify(data);
                    console.log(data);
                    if (data.code == 1) {
                        $(".shadow").addClass("shado");
                        $(".news_byID div").remove();
                        $("#news_byID_h3").text(data.data[0].companyname);
                        var count = data.data.length;
                        // "author": "中国证券网",
                        for (let i = 0; i < count; i++) {
                            var type0 = data.data[i].type == 1 ? btnText = ' 移除重要新闻' : btnText = " 设为重要新闻";
                            var codeView = `  <div class="box_border ${data.data[i].type == 1?"import_div":'' }" newsid=${data.data[i].newsid}><a href=${data.data[i].url} target="view_window">
                            <h4  style="float: left">${data.data[i].title} &nbsp;</h4></a><div class="explainView" newsid=${data.data[i].newsid}>——<span style="font-size: small"></span><label style="font-size: small">${"来源:" + data.data[i].author}</label><span class="btn updateNews" type=${data.data[i].type == 1 ? 0 : 1}><i class="icon-star"></i>${type0}</span>
                            <label style="font-size: small">${transDate(data.data[i].publishtime)}</label></div>
                            </div>`
                            $(".news_byID").append(codeView)
                        }
                        $(".updateNews").unbind("click");
                        $(".updateNews").click(function () {
                            var _timestamp = new Date().getTime();
                            var _secret = hex_md5(ip + '/NewsBack/UpdateNewsType?timestamp=' + _timestamp + salt);
                            var _newsId = parseInt($(this).parent().attr("newsid"));
                            var type = parseInt($(this).attr("type"));
                            var _this = $(this);
                            $.ajax({
                                type: "POST",
                                url: ip + '/NewsBack/UpdateNewsType?timestamp=' + _timestamp + '&secret=' + _secret + '&token=' + _token,
                                dataType: 'json',
                                data: JSON.stringify({
                                    "newsId": _newsId,
                                    "type": type
                                }),
                                headers: {
                                    "Content-Type": "application/json",
                                    "Accept": "application/json;charset=utf-8",
                                    // "token": "Zo0hVZ6QH3BoyyrLCp1dJO9qygX60uwrFJo1fWTkdbGFGKnEvblzgw%3D%3D"
                                    "token": _token
                                },
                                success: function (data) {
                                    // var result = JSON.stringify(data);
                                    console.log(data);
                                    if (data.code == 1) {
                                        if (_type == 0 && type == 1) {
                                            $(".divLi[newsid="+_newsId+"]").addClass("import_div");
                                            $(".news_byID div[newsid="+_newsId+"]").addClass("import_div");
                                            _this.html("<i class='icon-star'></i>移除重要新闻");
                                            _this.attr({"type": 0});

                                        }
                                        if (_type == 0 && type == 0) {
                                            $(".news_byID div[newsid="+_newsId+"]").removeClass("import_div");
                                            $(".divLi[newsid="+_newsId+"]").removeClass("import_div");
                                            _this.html("<i class='icon-star'></i>设为重要新闻");
                                            _this.attr({"type": 1});
                                        }
                                        if (_type == 1) {
                                            _this.parent().fadeOut();
                                        }
                                        // _type==1?alert("设置成功"):alert("移除重要新闻成功")
                                    }
                                    else {
                                        alert(data.message)
                                    }
                                },
                                error: function () {
                                    alert('请求失败');
                                },
                            });
                        })
                        $(".news_ID").fadeIn();
                        $(document).one('click',() => {$(".news_ID").fadeOut();$(".shadow").removeClass("shado");});
                        $(window).one('scroll',()=>{$(".news_ID").fadeOut();$(".shadow").removeClass("shado");})

                    }
                    else {
                        alert(data.message)
                    }
                },
                error: function () {
                    alert('请求失败');
                },
            });
        })
        //是否设置为重要新闻
        $(".updateNews").unbind("click");
        $(".updateNews").click(function () {
            var _timestamp = new Date().getTime();
            var _secret = hex_md5(ip + '/NewsBack/UpdateNewsType?timestamp=' + _timestamp + salt);
            var _newsId = parseInt($(this).parent().attr("newsid"));
            var type = parseInt($(this).attr("type"));
            var _this = $(this);
            $.ajax({
                type: "POST",
                url: ip + '/NewsBack/UpdateNewsType?timestamp=' + _timestamp + '&secret=' + _secret + '&token=' + _token,
                dataType: 'json',
                data: JSON.stringify({
                    "newsId": _newsId,
                    "type": type
                }),
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json;charset=utf-8",
                    // "token": "Zo0hVZ6QH3BoyyrLCp1dJO9qygX60uwrFJo1fWTkdbGFGKnEvblzgw%3D%3D"
                    "token": _token
                },
                success: function (data) {
                    // var result = JSON.stringify(data);
                    console.log(data);
                    if (data.code == 1) {
                        if (_type == 0 && type == 1) {
                            _this.parent().addClass("import_div");
                            _this.html("<i class='icon-star'></i>移除重要新闻");
                            _this.attr({"type": 0});

                        }
                        if (_type == 0 && type == 0) {
                            _this.parent().removeClass("import_div");
                            _this.html("<i class='icon-star'></i>设为重要新闻");
                            _this.attr({"type": 1});
                        }
                        if (_type == 1) {
                            _this.parent().fadeOut();
                        }
                        // _type==1?alert("设置成功"):alert("移除重要新闻成功")
                    }
                    else {
                        alert(data.message)
                    }
                },
                error: function () {
                    alert('请求失败');
                },
            });
        })
    }

    $(window).scroll(function () {
        //下面这句主要是获取网页的总高度，主要是考虑兼容性所以把Ie支持的documentElement也写了，这个方法至少支持IE8
        $(".news_ID").fadeOut();
        var htmlHeight = $(document).height();
        //clientHeight是网页在浏览器中的可视高度，
        var clientHeight = $(window).height();
        //scrollTop滚动条到顶部的垂直高度
        var scrollTop = $(document).scrollTop();
        //通过判断滚动条的top位置与可视网页之和与整个网页的高度是否相等来决定是否加载内容；
        var he = scrollTop + clientHeight;
        if (he >= htmlHeight * 1) {
            _page += 1;
            getNews(_orderType, _page, _type)
        }
        //console.log("滚动条位置：" + scrollTop);
        //console.log("可视高度：" + clientHeight);
        //console.log("网页总高度" + htmlHeight);
    });
    $(".news_ID").click((event)=>{
        event=event||window.event;
        event.stopPropagation();
    });
})